package com.duojuhe.websocket.subscriber.listener;


import com.alibaba.fastjson.JSONObject;
import com.duojuhe.coremodule.chat.im.handle.ChatHandleCommonKit;
import com.duojuhe.coremodule.chat.im.handle.ChatHandleListenerKit;
import com.duojuhe.websocket.EventCodes;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;

import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;


/**
 * @Description 集群聊天消息监听器
 * @Date 2020/3/29 15:07
 */
@Slf4j
@Component
public class ImMessageListener implements MessageListener {
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private ChatHandleListenerKit chatHandleListenerKit;

    @Override
    public void onMessage(Message message, byte[] pattern) {
        RedisSerializer<JSONObject> valueSerializer = redisTemplate.getValueSerializer();
        JSONObject jsonObject = valueSerializer.deserialize(message.getBody());
        log.info("监听集群IM Websocket消息--- {}", jsonObject);
        //将字符串转成对象
        if (jsonObject == null) {
            log.info("监听集群IM Websocket消息为空");
            return;
        }
        log.info("监听集群IM Websocket消息--- {}", jsonObject);
        //消息事件类型
        String eventType = jsonObject.getString("eventType");
        //消息事件内容
        JSONObject jsonMessageData = jsonObject.getJSONObject("messageData");
        if (jsonMessageData == null) {
            log.info("监听集群IM Websocket消息jsonMessageData不可为空");
            return;
        }
        if (EventCodes.EVENT_TALK.getEvent().equals(eventType)) {
            //聊天事件
            chatHandleListenerKit.eventTalkHandle(jsonMessageData);
        } else if (EventCodes.EVENT_ONLINE_STATUS.getEvent().equals(eventType)) {
            //在线状态事件
            chatHandleListenerKit.eventOnlineStatusHandle(jsonMessageData);
        } else if (EventCodes.EVENT_KEYBOARD.getEvent().equals(eventType)) {
            //键盘事件
            chatHandleListenerKit.eventKeyboardHandle(jsonMessageData);
        } else if (EventCodes.EVENT_REVOKE_TALK.getEvent().equals(eventType)) {
            //撤回事件
            chatHandleListenerKit.eventRevokeHandle(jsonMessageData);
        } else if (EventCodes.EVENT_DELETE_TALK.getEvent().equals(eventType)) {
            //删除事件
            chatHandleListenerKit.eventDeleteHandle(jsonMessageData);
        }

    }


}